import { createRouter, createWebHashHistory } from "vue-router";
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    component: () => import("@/views/login/Login.vue"),
    meta: { title: "登录" }
  },

  {
    path: "/seeker",
    component: () => import("@/views/adduser/SeekerView.vue"),
    meta: { title: "入会申请" }
  },
  {
    path: "/home", // 管理后台的父路由
    component: () => import("@/views/Home.vue"),
    children: [
      {
        path: "/dashboard",
        component: () => import("@/views/DashBoard.vue"),
        meta: { title: "首页", requiresAuth: true }
      },
      {
        path: "/user",
        component: () => import("@/views/user/User.vue"),
        // requiresAuth添加需要认证标记
        meta: { title: "用户", requiresAuth: true }
      },
      {
        path: "/seal",
        component: () => import("@/views/seal/seal.vue"),
        meta: { title: "入会申请" }
      },
      {
        path: "/role",
        component: () => import("@/views/role/role.vue"),
        // requiresAuth添加需要认证标记
        meta: { title: "角色", requiresAuth: true }
      },
      {
        path:"/admin",
        component:() =>import("@/views/adduser/AdminView.vue"),
        meta:{title: "入所审批",requiresAuth: true}
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = `${to.meta.title || '默认标题'} | 系统名称`

  // 不需要认证的白名单
  const publicPages = ['/login',  '/seeker']

  // 检查是否需要认证
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const hasToken = sessionStorage.getItem("token")

  if (requiresAuth && !hasToken) {
    // 需要认证但未登录，跳转到登录页
    next('/login')
  } else if (hasToken && to.path === '/login') {
    // 已登录但访问登录页，跳转到后台首页
    next('/dashboard')
  } else if (publicPages.includes(to.path) || hasToken) {
    // 公开页面或已认证，直接放行
    next()
  } else {
    // 其他情况（如需要认证但未登录访问非公开页面）
    next('/login')
  }
})

export default router
